package com.hexb.core.utils

import com.hexb.core.model.Model

/**
 * @Package : com.hexb.core.utils
 * @Author : hexb 
 * @Date : 2018-08-17 17:19
 */
class ObjectHelper {

    static Map getSortedProperties(Object obj, String... excludeFields) {
        def map = obj.properties
        map.remove('metaClass')
        map.remove('class')
        if (excludeFields) {
            excludeFields.each {
                map.remove(it)
            }
        }
        Map linkedMap = new TreeMap()
        linkedMap += map
        linkedMap
    }

    static String getSortedPropertiesString(Object obj, String keyValueConcatChar, String propertyConcatChar, String... excludeFields) {
        def map = getSortedProperties(obj, excludeFields)
        map.entrySet()
                .findAll { it.value }
                .collect { "${it.key}${keyValueConcatChar}${it.value}" }
                .join(propertyConcatChar)
    }

    static String getSortedPropertiesString(Object obj, String... excludeFields) {
        getSortedPropertiesString(obj, '=', '&', excludeFields)
    }


    static <T> T getProperty(Object bean, String property, T defaultValue) {
        try {
            bean."$property"
        } catch (e) {
        }
        return defaultValue
    }

    static String getProperty(Object bean, String property) {
        getStringProperty(bean, property)
    }

    static String getStringProperty(Object bean, String property) {
        try {
            bean."$property"
        } catch (e) {
        }
        null
    }

    static <T> Map<Object, T> listToMap(List<T> list, String key) {
        def map = [:]
        list.forEach({
            map << [(it."$key"): it]
        })
        map
    }
}
